#include "grouprequestlist.h"
#include "ui_grouprequestlist.h"
#include <QPushButton>
#include <QLabel>
#include <QJsonObject>
#include "Business/inputhandler.h"

GroupRequestList::GroupRequestList(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::GroupRequestList)
{
    ui->setupUi(this);

    setWindowTitle("群组申请列表");
}


GroupRequestList::~GroupRequestList()
{
    delete ui;
}

void GroupRequestList::addAGroupRequest(int avatar, QString userAccount, QString groupName)
{
    QListWidgetItem* newListItem = new QListWidgetItem();

    ui->groupList->addItem(newListItem);
    QHBoxLayout* layout = new QHBoxLayout(this);
    QLabel* avatarPic = new QLabel(this);
    QLabel* acc = new QLabel(this);
    // set avatarPic size and image
    avatarPic->setFixedSize(QSize(50, 50));

    QString imagePath;
    imagePath = ":/icon/avatar/" + QString::number(avatar) + ".svg";
    QImage ava(imagePath);
    avatarPic->setPixmap(QPixmap::fromImage(ava));
    // set acc name

    acc->setText(userAccount + " 申请加入: " + groupName);
    QPushButton* accept = new QPushButton("接受", this);
    QPushButton* reject = new QPushButton("拒绝", this);

    accept->setProperty("UserAccount", userAccount);
    accept->setProperty("GroupName", groupName);
    accept->setProperty("Status", "accept");

    reject->setProperty("UserAccount", userAccount);
    reject->setProperty("GroupName", groupName);
    reject->setProperty("Status", "reject");

    QObject::connect(accept, &QPushButton::clicked, this, &GroupRequestList::buttonClicked);
    QObject::connect(reject, &QPushButton::clicked, this, &GroupRequestList::buttonClicked);

    layout->addWidget(avatarPic);
    layout->addWidget(acc);
    layout->addWidget(accept);
    layout->addWidget(reject);

    QWidget* container = new QWidget(this);
    container->setLayout(layout);

    newListItem->setSizeHint(container->sizeHint());
    ui->groupList->setItemWidget(newListItem, container);
}

void GroupRequestList::buttonClicked()
{
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (button) {
        // get user account
        QString userAccount = button->property("UserAccount").toString();
        // get GroupName
        QString groupName = button->property("GroupName").toString();
        // get status
        QString status = button->property("Status").toString();

        QJsonObject in, out;
        in["UserAccount"] = userAccount;
        in["GroupName"] = groupName;
        in["Status"] = status;

        InputHandler::getInstance()["GroupRequestList::buttonClicked"](in, out);
        // refresh user list

        on_btnRefreshRequestList_clicked();
    }
}

void GroupRequestList::clearGroupRequestList()
{
    ui->groupList->clear();
}

void GroupRequestList::on_btnRefreshRequestList_clicked()
{
    ui->groupList->clear();
    QJsonObject in, out;
    InputHandler::getInstance()["GroupRequestList::on_btnRefreshRequestList_clicked"](in, out);
}

